<template>
  <div ref="myChart" :style="style"></div>
</template>
<script>
import * as echarts from "echarts";
export default {
  data() {
    return {
      myChart: null,
    };
  },
  props: {
    height: {
      type: String,
      default: "400px",
    },
    width: {
      type: String,
      default: "100%",
    },
    option: {
      type: Object,
      default: null,
    },
  },
  computed: {
    style() {
      return {
        height: this.height,
        width: this.width,
      };
    },
  },
  watch: {
    width() {
      if (this.myChart) {
        this.myChart.resize({
          animation: {
            duration: 300,
          },
        });
      }
    },
    option() {
      if (this.option && !this.myChart) {
        this.init();
      }
      if (this.myChart) {
        this.myChart.setOption(this.option, {
          notMerge: true,
          lazyUpdate: true,
        });
      }
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.init();
    });
  },
  methods: {
    init() {
      if (!this.option) return;
      this.myChart = echarts.init(this.$refs.myChart);
      this.myChart.setOption(this.option);
      window.addEventListener("resize", () => {
        this.myChart.resize();
      });
      let _this = this;
      this.myChart.on("click", function (params) {
        _this.$emit("emitIdx", params.dataIndex);
      });
    },
  },
};
</script>